package com.example.deepschool.service.TempDownload;

import com.example.deepschool.Model.Response.ResponseData;
import com.example.deepschool.enums.GlobalVariables_String;
import com.example.deepschool.exception.CustomException;
import com.example.deepschool.util.IO;
import com.example.deepschool.util.Redis;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

@Service
public class TempDownloadImpl implements TempDownload {
	
	@SneakyThrows
	@Override
	public ResponseData Download (String TempUUID, String host, String range) {
		try {
			long start = 0;
			if (range != null) {
				start = Long.parseLong(range.split("=")[1].split("-")[0]);
			}
			String[] tempInfo = Verify(TempUUID, host);
			String Path = GlobalVariables_String.File_Path_CourseResource.getValue() + tempInfo[1];
			return IO.DownloadFile(Path, tempInfo[0], start, range);
		} catch (Exception e) {
			throw new CustomException(400, e.getMessage());
		}
	}
	
	private String[] Verify (String TempUUID, String host) {
		if (! Redis.EXISTS(TempUUID)) {
			throw new RuntimeException("临时下载链接已失效");
		}
		String Host = Redis.HGET(TempUUID, "host");
		if (! Host.equals("0")) {
			if (! Host.equals(host)) {
				throw new RuntimeException("临时下载链接已失效");
			}
		} else {
			Redis.HSET(TempUUID, "host", host);
		}
		String name = Redis.HGET(TempUUID, "name");
		String address = Redis.HGET(TempUUID, "address");
		return new String[] {name, address};
	}
	
}
